package com.nf.mvc.util;


import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;

import java.util.HashSet;
import java.util.Set;

public interface ScanUtils {

    /**
     * 指定同样的包或者有包含的关系的包时，类是不会被重复扫描到结果中的
     * 业界比较典型扫描用的工具有ClassGraph，Reflections，huTool之类
     *
     * @param packageNames 要扫描的包
     * @return 扫描到的所有Class信息
     */
    static Set<Class<?>> scan(String... packageNames) {
        Set<Class<?>> allScannedClasses = new HashSet<>();
        ClassGraph classGraph = new ClassGraph();
        classGraph.enableAllInfo();
        classGraph.acceptPackages(packageNames);
        ClassInfoList allClasses;
        try (ScanResult scanResult = classGraph.scan()) {
            allClasses = scanResult.getAllClasses();
            for (ClassInfo classInfo : allClasses) {
                // 这些扫描到的类使用的类加载器与DispatcherServlet的类加载器是同一个
                Class<?> scannedClass = classInfo.loadClass();
                allScannedClasses.add(scannedClass);
            }
        }

        return allScannedClasses;
    }
}
